﻿using rbac.contracts.Dto.Input;
using rbac.contracts.Dto.Output;
using rbac.contracts.Interface;
using rbac.domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace rbac.services
{
    public class RolePermissionService :ServiceBase, IRolePermissionService
    {
        IRolePermissionRepository _rolePermissionRepository;

        public RolePermissionService(IRolePermissionRepository rolePermissionRepository)
        {
            _rolePermissionRepository = rolePermissionRepository;
        }

        public int DistributeRolePermission(DistributeRolePermissionsInput input)
        {
            return _rolePermissionRepository.DistributeRolePermission(input.RoleId,input.PermissionList);
        }

        /// <summary>
        /// 权限角色获取权限列表
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<PermissionDto> GetPermissionByRoleId(int roleId)
        {
            var permissions=_rolePermissionRepository.GetPermissionByRoleId(roleId);
            List<PermissionDto> resilt = new();
            foreach(var permission in permissions.Where(x=>x.ParentId==0))
            {
                var dto=_mapper.Map<PermissionDto>(permission);
                var child = permissions.Where(x => x.ParentId == permission.Id);
                if (child.Any())//判断是否有数据
                {
                    dto.Child = _mapper.Map<List<PermissionDto>>(child);
                }
                resilt.Add(dto);
            }
            return resilt;
        }

    }
}
